import { MES_LXK_ApiHost } from '@/utils/Interceptors'

// 定义数据类型
export interface DefectiveItemDistribution {
  distributionId: number
  time: string
  defectItemId: number
  defectItemName: string
  defectItemNumber: string
  quantity: number
  totalQuantity: number
  percentage: number
  isDelete: boolean
}

export interface ApiResponse {
  code: number
  msg: string
  data: DefectiveItemDistribution[]
}

export interface SearchParams {
  startTime?: string
  endTime?: string
  defectItemNumber?: string
  DefectItemName?: string
}

// 获取所有不良品项分布数据
export const getAllDistributions = async (params?: SearchParams) => {
  if (!params) {
    return await MES_LXK_ApiHost.get<ApiResponse>('/api/Distribution/GetAllDistributions')
  }
  
  // 过滤掉空值参数
  const filteredParams: any = {}
  Object.keys(params).forEach(key => {
    if (params[key as keyof SearchParams] && params[key as keyof SearchParams] !== '') {
      filteredParams[key] = params[key as keyof SearchParams]
    }
  })
  
  return await MES_LXK_ApiHost.get<ApiResponse>('/api/Distribution/GetAllDistributions', { 
    params: filteredParams 
  })
}

// 根据条件搜索不良品项分布数据
export const searchDistributions = async (params: SearchParams) => {
  // 过滤掉空值参数
  const filteredParams: any = {}
  Object.keys(params).forEach(key => {
    if (params[key as keyof SearchParams] && params[key as keyof SearchParams] !== '') {
      filteredParams[key] = params[key as keyof SearchParams]
    }
  })
  
  console.log('API层过滤后的参数:', filteredParams) // 调试API层参数
  
  return await MES_LXK_ApiHost.get<ApiResponse>('/api/Distribution/GetAllDistributions', { 
    params: filteredParams 
  })
}

// 导出不良品项分布数据
export const exportDistributions = async (params?: SearchParams) => {
  return await MES_LXK_ApiHost.get('/api/Distribution/ExportDistributions', { 
    params,
    responseType: 'blob',
    headers: {
      'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, */*'
    }
  })
}
